package com.anmi.alfred.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RestClientConfig {

  @Autowired private ElasticsearchProp elasticsearchProp;

  @Bean
  public RestHighLevelClient restHighLevelClient() {

    String[] nodes = elasticsearchProp.getNodes().split(",");
    HttpHost[] hosts = new HttpHost[nodes.length];
    for (int i = 0; i < nodes.length; i++) {
      hosts[i] = HttpHost.create(nodes[i]);
    }
    RestClientBuilder restClientBuilder = RestClient.builder(hosts);
    // 设置连接时间为30秒，socket通信时间为5分钟
    restClientBuilder.setRequestConfigCallback(
        requestConfigBuilder ->
            requestConfigBuilder.setConnectTimeout(30000).setSocketTimeout(300000));

    if (StringUtils.isNotBlank(elasticsearchProp.getUser())
        && StringUtils.isNotBlank(elasticsearchProp.getPassword())) {
      final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(
          AuthScope.ANY, new UsernamePasswordCredentials("elastic", "AFE#qr33"));

      restClientBuilder.setHttpClientConfigCallback(
          httpAsyncClientBuilder -> {
            httpAsyncClientBuilder.disableAuthCaching();
            return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
          });
    }

    return new RestHighLevelClient(restClientBuilder);
  }
}
